package com.corpgovernment.common.utils;

import com.ctrip.corp.obt.generic.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.IdentityHashMap;
import java.util.List;

/**
 * @author James Smith
 * @see com.corpgovernment.organization.util.StrUtils#fieldRemoveWarp(Object)
 */
@Slf4j
public class ObjectStringTrimUtils {


    private static boolean isPrimitiveOrJdkClass(Class<?> clazz) {
        // 判断是否是基本类型或JDK自带的类
        boolean isPrimitiveOrJdk = clazz.isPrimitive() || clazz.getPackage() != null && clazz.getPackage().getName().startsWith("java.");

        // 判断是否是你的项目的类
        boolean isProjectClass = clazz.getPackage() != null && (clazz.getPackage().getName().startsWith("com.corpgovernment") || clazz.getPackage().getName().startsWith("com.ctrip"));

        return isPrimitiveOrJdk || !isProjectClass;
    }


    /**
     * TODO 该静态变量后续需要放到apollo配置中心
     */
    private static final String[] DATE_TIME_PATTERNS = {
            "yyyy-MM-dd HH:mm",
            "yyyy-MM-dd HH:mm:ss",
            "yyyy/MM/dd HH:mm",
            "yyyy/MM/dd HH:mm:ss",
            "yyyy-MM-dd'T'HH:mm:ss.SSSZ",
            "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",
            "yyyy-MM-dd'T'HH:mm:ss'Z'",
            "yyyy-MM-dd'T'HH:mm:ssZ",
            "EEE, dd MMM yyyy HH:mm:ss zzz",
            "EEE, dd MMM yyyy HH:mm:ss 'GMT'",
            "EEE, dd MMM yyyy HH:mm:ss",
            "dd/MM/yyyy HH:mm:ss",
            "dd-MMM-yyyy HH:mm:ss",
            "dd-MMM-yyyy",
            "MM/dd/yyyy HH:mm",
            "MM/dd/yyyy HH:mm:ss",
            "MM-dd-yyyy HH:mm",
            "MM-dd-yyyy HH:mm:ss"
    };

    private static boolean isDateTime(Object value) {
        if (!(value instanceof String)) {
            return false;
        }
        // 字符串不包含数字，直接返回false
        if (!((String) value).matches(".*\\d.*")) {
            return false;
        }

        String str = (String) value;
        for (String pattern : DATE_TIME_PATTERNS) {
            try {
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
                LocalDateTime.parse(str, formatter);
                return true;
            } catch (DateTimeParseException ignored) {
            }
        }
        return false;
    }

    private static Object trimAll(Object obj, IdentityHashMap<Object, Boolean> visited) {
        if (obj == null) {
            return null;
        }

        // 判断字段是否是基本数据类型或 JDK 自带的类
        if (isPrimitiveOrJdkClass(obj.getClass())) {
            return obj;
        }

        // 检查对象是否已经被处理过
        if (visited.containsKey(obj.getClass())) {
            return obj;
        }
        // 将对象添加到已访问集合
        visited.put(obj, true);

        Field[] declaredFields = obj.getClass().getDeclaredFields();
        Arrays.stream(declaredFields).forEach(field -> {
            // 如果字段是 final 的，跳过
            if (Modifier.isFinal(field.getModifiers())) {
                return;
            }

            field.setAccessible(true);
            try {
                Object value = field.get(obj);
                if (value == null) {
                    return;
                }

                if (value instanceof String) {
                    if (isDateTime(value)) {
                        // 保留时间字符串不做处理
                        return;
                    } else {
                        field.set(obj, ((String) value).replaceAll("\\s+", ""));
                    }
                    return;
                }

                if (value instanceof Collection) {
                    Collection<?> collection = (Collection<?>) value;
                    List<Object> newCollection = new ArrayList<>(collection.size());
                    collection.forEach(item -> {
                        if (item instanceof String) {
                            newCollection.add(((String) item).replaceAll("\\s+", ""));
                        } else if (!isPrimitiveOrJdkClass(item.getClass())) {
                            newCollection.add(trimAll(item, visited));
                        } else {
                            newCollection.add(item);
                        }
                    });
                    try {
                        field.set(obj, newCollection);
                    } catch (IllegalAccessException e) {
                        log.error("fieldRemoveWarp: ", e);
                    }
                    return;
                }

                if (!isPrimitiveOrJdkClass(value.getClass())) {
                    trimAll(value, visited);
                }
            } catch (IllegalAccessException e) {
                log.error("fieldRemoveWarp: ", e);
            }
        });
        return obj;
    }


    /**
     * 字符串剔除空格和空行<br>
     * * 不支持数组、map以及对象中的数组与map<br>
     * * 不支持循环引用<br>
     * * 不支持多线程<br>
     *
     * @see com.corpgovernment.organization.util.StrUtils#fieldRemoveWarp(Object)
     */
    public static Object allFieldRemoveWarp(Object obj) {
        log.info("allFieldRemoveWarp before: {}", JsonUtils.toJsonString(obj));
        // 目前用来处理循环引用的问题
        IdentityHashMap<Object, Boolean> visited = new IdentityHashMap<>();

        Object o = trimAll(obj, visited);

        log.info("allFieldRemoveWarp after: {}", JsonUtils.toJsonString(o));

        return o;
    }
}
